package com.lsmw.commonutils;
/*
 *ClassName:R
 *UserName:二号男嘉宾
 *CreateTime:2020/11/26 20:43
 *Description:统一返回的结果
 */

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Data
public class R {

    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<>();

    private R() {
    }

    //返回请求数据成功
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.OK);
        r.setMessage("OK");
        return r;
    }

    //创建数据成功
    public static R created() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.CREATED);
        r.setMessage("CREATED");
        return r;
    }

    //删除成功
    public static R noContent() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.NO_CONTENT);
        r.setMessage("NO_CONTENT");
        return r;
    }

    //请求有误
    public static R invalidRequest() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.INVALID_REQUEST);
        r.setMessage("INVALID_REQUEST");
        return r;
    }

    //用户没有权限
    public static R unauthorized() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.Unauthorized);
        r.setMessage("Unauthorized");
        return r;
    }

    //请求资源不存在
    public static R notFound() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.NOT_FOUND);
        r.setMessage("NOT_FOUND");
        return r;
    }

    //服务器发生错误
    public static R internalServerError() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.INTERNAL_SERVER_ERROR);
        r.setMessage("INTERNAL_SERVER_ERROR");
        return r;
    }

    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    public R message(String message) {
        this.setMessage(message);
        return this;
    }

    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map) {
        this.setData(map);
        return this;
    }

    public R setResponseCode(HttpServletResponse response){
        response.setStatus(this.code);
        return this;
    }

}
